import React, { useState, forwardRef, useImperativeHandle } from "react";
import { Checkbox } from "antd";
import { text_check } from "../../utils";

const MyCheckBox = forwardRef(function MenuCheckBox(props, parentRef) {
  const CheckboxGroup = Checkbox.Group;

  const { item } = props;
//   console.log(item);
  const plainOptions = item.children.map((ele) => ele.menu_index);
  const groupOptions = item.children.map((child) => {
    return {
      label: text_check(child),
      value: child.menu_index,
      key: child.menu_index,
    };
  });
  const [checkedList, setCheckedList] = useState(
    item.child_checked ? item.child_checked : []
  );
  const checkAll = plainOptions.length === checkedList.length;
  const indeterminate =
    checkedList.length > 0 && checkedList.length < plainOptions.length;
  const onChange = (list) => {
    setCheckedList(list);
  };
  const onCheckAllChange = (e) => {
    setCheckedList(e.target.checked ? plainOptions : []);
  };

  useImperativeHandle(parentRef, () => {
    // return返回的值就可以被父组件获取到,没返回的值就获取不到
    return {
      checkedList,
    };
  });

  return (
    <div className="checked_group_box">
      <Checkbox
        indeterminate={indeterminate}
        onChange={onCheckAllChange}
        checked={checkAll}
      >
        {text_check(item)}
      </Checkbox>
      <CheckboxGroup
        options={groupOptions}
        value={checkedList}
        onChange={onChange}
      />
    </div>
  );
});
export default MyCheckBox;
